var isFirstCommon = true;
cc.Class({
    extends: require('UI-PanelWindow'),

    properties: {
        selectPlayer: require('SelectPlayer'),
        coin: cc.Label,
        close: [cc.Node],
        n_currentPlane: null,       //当前选择的飞机
        friendlyLinksNode: [cc.Node],    //友情链接节点
        gateConfigRes : cc.JsonAsset,
        power:cc.Label,   //当前能量
        tip:[cc.Node],
        // mask:cc.Node,
        currentPass:cc.Label,   //当前最大关卡
        count:cc.Node,
        startBtn:cc.Button,
        upLevel : require('UpLevel'),
        OnlineReward:require('OnlineReward'),
        moveCoin:cc.Node,
        scroll:require('UI-ScrollSelect')
    },

    // LIFE-CYCLE CALLBACKS:


  
    onLoad() {
        this._super();
        // global.noVideoPlane=global.Data.currentPlane;
        
        this.n_currentPlane = 0;
        // this.mask.active=true;
        this.supId=Math.floor(global.Data.currentPass);//副武器
        this.supId=Math.min(this.supId,9)
        var lastUseSup=cc.sys.localStorage.getItem('usedSup')
        if(!!lastUseSup && this.supId>lastUseSup){
            this.supId=parseInt(lastUseSup)<0?0:parseInt(lastUseSup);
        }
        // cc.sys.localStorage.setItem('usedSup',this.supId)
        global.supId=this.supId;

    //    this.count.on(cc.Node.EventType.TOUCH_START,this.onTouchStart,this);
    //    this.count.on(cc.Node.EventType.TOUCH_MOVE,this.onTouchMove,this);
    //    this.count.on(cc.Node.EventType.TOUCH_END,this.onTouchEnd,this);
       
       global.Event.on('changePlane',this.changePlane.bind(this),this);
       global.Event.on('signed',this.hide.bind(this),this);
       global.Event.on('showSup',this.changeSup.bind(this),this);
       global.Event.on('STARTBTN',this.changeBtn.bind(this),this);
       SoundMgr.playMusic('./Audio/bgm_main');
       /*var rc = require('RewardComponent');
       this.has = rc.hasVideo();//是否能看视频*/

       this.noVideoPlaneArr=[0]
       var siginCount=global.Data.signIn.signCount;
       var gatesCount=global.Data.currentPass;
       if(siginCount>=3){
           this.noVideoPlaneArr.push(2)
       }
       if(gatesCount>=5){
           this.noVideoPlaneArr.push(1)
       }
       
       this.maskBg=cc.find('maskBg',this.node);
       this.maskBg.active=false;
       this.hasWatchVideoJoin = false;// 需要看视频才能进入
       
       global.Data.prop=[false,false,false]
       if(global.Data.prop2){
        global.Data.prop=[true,true,true]
       }
       cc.find('upgradePanel/panel',this.node).on(cc.Node.EventType.TOUCH_START,this.clickJiantou,this);
       cc.find('upgradePanel/jiantoukuang',this.node).on(cc.Node.EventType.TOUCH_START,this.clickJiantou,this);
    //    this.OnlineReward.scale=global.Data.mainArmsLevel+1
    },
    onDestroy() {
        global.Event.off('signed');
        global.Event.off('changePlane');
        global.Event.off('showSup');
        global.Event.off('STARTBTN');
    },
    changeBtn(data){
        if(this.startBtn){
            this.hasWatchVideoJoin = data;
            // if(global.Data.currentPass<10){
            //     this.startBtn.interactable =!data;
            // }
            // cc.find('btnWujin',this.node).getComponent(cc.Button).interactable =!data;
        }
    },
    changeSup(data){
        this.supId=data.data;
        global.supId=this.supId;
        cc.sys.localStorage.setItem('usedSup',this.supId)
    },
    hide(){
        cc.find('sigin',this.node).active=false
    },

    changePlane(data){
        this.setPlane(data.data,true,this.supId)
    },

    onTouchStart(event){
        this.startPoint = this.count.convertToNodeSpace(event.getLocation());
    },
    onTouchMove(event){},
    onTouchEnd(event){
        this.endPoint = this.count.convertToNodeSpace(event.getLocation());
        if(this.endPoint.x-this.startPoint.x>10){
            this.choosePlane(event,-1)
            // this.mask.active=true;
        }
        if(this.endPoint.x-this.startPoint.x<-10){
            this.choosePlane(event,1)
            // this.mask.active=true;
        }
    },
    start() {
        this.setPlane(this.n_currentPlane,true,this.supId)
        this.node._uimgrloadEnd = true;
        this.onWechatShow = function () {
            console.log('onWechatShow')
            this.checkMessage();
        }.bind(this)
        if (CC_WECHATGAME) {
            wx.onShow(this.onWechatShow)
        }
        this.checkMessage();

        if (!global.Data.isCheck) {
            // global.EJMgr.pushUI('inviteReward/inviteReward');
        }
        // global.Data.currentPass=3
        !CC_WECHATGAME && (global.Data.currentPass=1)
        var daguan=Math.floor(global.Data.currentPass/4)+1;
        var xiaoguan=global.Data.currentPass-Math.floor(global.Data.currentPass/4)*4+1;
        global.gates=daguan+'-'+xiaoguan;
        
        if(global.Data.currentPass<10){
            this.currentPass.string='第'+(global.Data.currentPass+1)+'关';
        }else{
            this.currentPass.string='敬请期待'
            this.startBtn.interactable =false
        }
        var self = this;
        let day = global.Common.calcDetailDay(new Date(global.Data.registerTimeTick),new Date())
        if((isFirstCommon && day >= 1) || (global.lastGameResult && global.gates && global.gates.split('-')[1] > 1)){
            var node = global.EJMgr.pushUI('Common/KnockEgg');
            var coin =Math.ceil(200*(global.Data.mainArmsLevel+1)*Math.pow(1.2,global.Data.mainArmsLevel))+Math.ceil(200*(global.Data.mainArmsLevel+2)*Math.pow(1.2,global.Data.mainArmsLevel+1))+Math.ceil(200*(global.Data.mainArmsLevel+3)*Math.pow(1.2,global.Data.mainArmsLevel+2));
            coin= Math.max(Math.floor(coin/3),500)
            node.getComponent('KnockEgg').setOptions({
                coin:coin,
                cb:function(status){
                    let c = coin*(status == 1? 1 : 3);
                    self.httpGet('/game/gameUser','attrAdd',{propName: "goldCoin",count:c},function(err,res){
                        if(!err){
                            global.Data.goldCoin += c
                        }
                    })
                    global.EJMgr.pushUI("Eject/EveryDayGift")
                }
            })
        } else {
            global.EJMgr.pushUI("Eject/EveryDayGift")
        } 
    },
    onEnterWindowBegin(){

    },


    clickMoreFriend(e,d){
        var more=cc.find('moreFriend',this.node);
        if(d=='left'){ 
            this.maskBg.active=true;
            more.runAction(cc.sequence(cc.moveTo(0.5,cc.v2(-30,-150)),cc.moveTo(0.1,cc.v2(-80,-150))))
        }else if(d=='right'){
            this.maskBg.active=false;
            more.runAction(cc.sequence(cc.moveTo(0.1,cc.v2(-30,-150)),cc.moveTo(0.5,cc.v2(-710,-150))))
        }
    },


    showFriendLink(){
        if(!global.Data.friendlyLinks){
            return
        }
        

        // function left(element) {
        //     return element.sceneName == '大厅' && element.area=='1';
        //     }

        // var leftArr = global.Data.friendlyLinks.filter(left);
        // function bottom(element) {
        //     return element.sceneName == '大厅' && element.area=='2';
        // }

        // var bottomArr = global.Data.friendlyLinks.filter(bottom);
        
        // //左侧友情链接
        // var friendLink=cc.find('moreFriend/friendLink',this.node);
        // for(let i=0;i<friendLink.children.length;i++){
        //     if(leftArr[i]){
        //         friendLink.children[i].getComponent('FriendlyLink').setOptions(leftArr[i]);
        //         if(i%2===0){//skewTo
        //             friendLink.children[i].runAction(cc.repeatForever(cc.sequence(cc.delayTime(0.4),cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0))))
        //         }else{
        //             friendLink.children[i].runAction(cc.repeatForever(cc.sequence(cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0),cc.delayTime(0.4))))
        //         }
        //     }else{
        //         friendLink.children[i].active=false
        //     }
        // }
        
        // //底部友情链接
        // var bottomFriend=cc.find('friendLinkBottom',this.node)
        // for(let i=0;i<bottomFriend.children.length;i++){
        //     if(bottomArr[i]){
        //         bottomFriend.children[i].getComponent('FriendlyLink').setOptions(bottomArr[i]);
        //         if(i%2===0){//skewTo
        //             bottomFriend.children[i].runAction(cc.repeatForever(cc.sequence(cc.delayTime(0.4),cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0))))
        //         }else{
        //             bottomFriend.children[i].runAction(cc.repeatForever(cc.sequence(cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0),cc.delayTime(0.4))))
        //         }
        //     }else{
        //         bottomFriend.children[i].active=false
        //     }
            
        // }

    },

    clickJiantou(){
        var upgradePanel=cc.find('upgradePanel',this.node);
        var bottomFriend=cc.find('friendLinkBottom',this.node)
        var jiantou=cc.find('upgradePanel/jiantoukuang/jiantou',this.node);
        // var moveY=bottomFriend.height;
        if(jiantou.scaleY==1){
            jiantou.scaleY=-1;
            upgradePanel.runAction(cc.moveBy(0.2,cc.v2(0,bottomFriend.height)))
            // cc.log(bottomFriend.y,bottomFriend.height)
        }else if(jiantou.scaleY==-1){
            jiantou.scaleY=1;
            upgradePanel.runAction(cc.moveBy(0.2,cc.v2(0,-bottomFriend.height)))
        }
    },

    levelUpBg(){
        
    },

    choosePlane(e,d) {
        require('ParticlePool').clean();
        // this.mask.active=true;
        d=parseInt(d);
       this.n_currentPlane+=d;
       var isRight=true
       if(d===1){
            isRight=false
       }
       if(this.n_currentPlane==-1){
           this.n_currentPlane=2;
       }else if(this.n_currentPlane==3){
           this.n_currentPlane=0;
       }
       this.setPlane(this.n_currentPlane,isRight,this.supId);
    },

    upgrade(e,d){//升级按钮
        cc.log(d);
    },

    checkMessage() {
        var self = this;
        this.httpGet('/game/gameUser', 'checkLogin', {}, function (err, res) {
            // cc.log('res:',res)
            if (err) {
                let eject = global.EJMgr.pushUI('Eject/Alert');
                eject.getComponent('Alert').setOptions({
                    title: '提示', message: '缓存有错，需要重新登陆', autoClose: false, ok: function () {
                        if (CC_WECHATGAME) {
                            global.Platform.cleanResource(function () {
                                cc.game.restart();
                            })
                        } else {
                            cc.sys.localStorage.clear();
                            cc.game.restart();
                        }
                    }
                })
                return;
            }
            // if (res.signIn.hasSign) {
                // global.Loader.loadResources('SignIn', function () {
                //     global.EJMgr.pushUI('SignIn/SignIn')
                // })
            // }
            Object.assign(global.Data, res);
            self.upLevel.refershUI();
        })
    },

    onDestroy() {
        if (CC_WECHATGAME) {
            wx.offShow(this.onWechatShow);
        }
        isFirstCommon = false;
    },
    setPlane(id, data,supId) {
        for (let i = 0; i < this.close.length; i++) {
            this.close[i].active = false
        }
        for (let i = 0; i < this.tip.length; i++) {
            this.tip[i].active = false
        }
        this.n_currentPlane = id;
        this.tip[this.n_currentPlane].active=true
        var self = this;
        cc.loader.loadRes('base/monster', cc.RawAsset, function (err, res) {
            global.DataConfig.monster = global.Common.readJson(res);
            
        })
        var siginCount=global.Data.signIn.signCount;
        var gatesCount=global.Data.currentPass;
        if(siginCount>=3){
            id=2
        }else if(gatesCount>=5){
            id=1
        }
        self.selectPlayer.setSupId(supId)
        cc.log('=========')
        self.scroll.init(id);
        self.selectPlayer.setPlane({
            type:2,
            index:id
        })
    },
    onClickRank() {
        SoundMgr.playButtonEffect()
        
        global.BannerAD.createBanner('adunit-4505ca0d79fae8df');
        cc.find('Canvas/RankLayer').active = true;
    },

    onClickMini() {
        SoundMgr.playButtonEffect()
        global.Loader.loadResources('BossHandBook',function(){
            global.EJMgr.pushUI("BossHandBook/BossHandBook")
        })
    },
    
    onClickAddPowerCoin(e,d){
        SoundMgr.playButtonEffect()
        var add=global.EJMgr.pushUI("SelectPlane/addPowerCoin")
        add.getComponent('addPowerCoin').setOptions(d)
    },

    onClickEveryGift(){
        SoundMgr.playButtonEffect()
        global.EJMgr.pushUI("Eject/EveryDayGift")
    },
    onClickSigIn(){
        SoundMgr.playButtonEffect()
        global.EJMgr.pushUI("SignIn/SignIn")
    },

    onWindowFocus() {
        console.log('onWindowFocus')
        this.node.active = true;
    },
    onExitWindowBegin() {
        console.log('onEnterWindowBegin')
        this.node.active = false;
    },
    onEnterWindowEnd() {
        this.node.active = true;
    },

    setOptions(options) {
        if (options.qianghua) {
            this.node.active = false;
            global.EJMgr.pushUI('PlaneStrengthen/PlaneStrengthen')
        }
    },


    watchvideo(planeId){//是否要看视频
        // if(this.noVideoPlaneArr.length>=3)return true;
        for(let i=0;i<this.noVideoPlaneArr.length;i++){
            if(planeId==this.noVideoPlaneArr[i])return true
        }
        return false
    },


    onClick() {
        // if(global.Data.store.power <= 0){
        //     var add=global.EJMgr.pushUI("SelectPlane/addPowerCoin")
        //     add.getComponent('addPowerCoin').setOptions(0)
        //     return;
        // }
        global.enemyCount=0;
        var chooseProp=global.EJMgr.pushUI("SelectPlane/chooseProp")
        chooseProp.getComponent('chooseProp').setOptions(this.hasWatchVideoJoin)
    },

    wujin() {
        // if(global.Data.store.power <= 0){
        //     var add=global.EJMgr.pushUI("SelectPlane/addPowerCoin")
        //     add.getComponent('addPowerCoin').setOptions(0)
        //     return;
        // }
        
        global.gates = 0;
        global.enemyCount=0;
        global.bossDieCount = 0//无尽模式打boss个数
        SoundMgr.playSound('Audio/button')
        
        var chooseProp=global.EJMgr.pushUI("SelectPlane/chooseProp")
        chooseProp.getComponent('chooseProp').setOptions(this.hasWatchVideoJoin)
    },

    checkHaveFriendlyLink() {
        let friendlyLinks = [];
        global.Data.friendlyLinks.forEach(element => {
            if (element.sceneName == 'SelectPlane') friendlyLinks.push(element);
        });
        for (let i = 0; i < this.friendlyLinksNode.length; i++) {
            this.friendlyLinksNode[i].active = false;
        }
        let nodeName = ['中左', '中右'];
        for (let i = 0; i < friendlyLinks.length; i++) {
            let area = nodeName.indexOf(friendlyLinks[i].area);
            if (area != -1) {
                this.friendlyLinksNode[area].getComponent('FriendlyLink').setOptions(friendlyLinks[i]);
            }
        };
    },

    clickOnlineReward(){

        var self=this
        
        var coinNumber=self.OnlineReward.getCoins();
        if(coinNumber<=0){
            return;
        }
        if(!global.Data.isCheck && coinNumber>(global.Data.mainArmsLevel+1)*60){
            var options={
                successCb:function(){
                    cc.log('分享成功')
                    self.rewardCoin(coinNumber);
                }
            }
            global.WechatShare.share(options);
        }else{
            self.rewardCoin(coinNumber);
        }
    },

    moveCoinFun(){
        this.moveCoin.active=true;
        var arr=[cc.v2(0,90),cc.v2(0,-90),cc.v2(90,0),cc.v2(-90,0),cc.v2(70,70),cc.v2(-70,70),cc.v2(70,-70),cc.v2(-70,-70)]
        this.moveCoin.setPosition(cc.v2(310,-45));
        for(let i=0;i<this.moveCoin.children.length;i++){
            this.moveCoin.children[i].setPosition(cc.v2(0,0))
            this.moveCoin.children[i].runAction(cc.sequence(cc.moveTo(0.3,cc.v2(arr[i])),cc.moveTo(0.6,cc.v2(0,0))))
        }
        this.moveCoin.runAction(cc.sequence(cc.delayTime(0.3),cc.moveTo(0.6,cc.v2(-240,600)),cc.callFunc(()=>{
             this.moveCoin.active=false;
            SoundMgr.playSound('Audio/coin_get',1);
        })))
    },

    rewardCoin(number){
        var self=this


        self.httpGet('/game/gameUser','attrAdd',{propName: "goldCoin",count:number},function(err,res){
            if(!err){
                self.OnlineReward.cleanTime();
                self.moveCoinFun();
                global.Data.goldCoin += number
            }
        })
    },

    // update (dt) {},
});

